package controllers

import (
	"cangku/cache"
	"cangku/models"
	"cangku/pkg"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type UserController struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *UserController) Register() {
	var err error
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "用户名和密码不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	user := models.User{
		Username: username,
		Password: pkg.MD5(password),
	}

	if err = user.GetNameByUsername(); err != nil {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "系统错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	if user.ID > 0 {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "用户已存在,注册失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	user.Create()
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "注册成功",
		Data: user,
	}
	c.ServeJSON()
	return
}

func (c *UserController) Login() {
	var err error
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "用户名和密码不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	key := "Login_pwd_error_" + username
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if count >= 3 {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "错误次数超过3次,账号封禁两分钟",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	user := models.User{
		Username: username,
		Password: pkg.MD5(password),
	}

	if err = user.GetNameByUsername(); err != nil {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "系统错误",
			Data: nil,
		}
		c.ServeJSON()
	}

	if user.ID == 0 {
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "用户不存在,登录失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	if user.Password != pkg.MD5(password) {

		cache.Rdb.Incr(cache.Ctx, key)
		if count == 2 {
			cache.Rdb.Expire(cache.Ctx, key, time.Minute)
		}
		c.Data["json"] = Res{
			Code: 500,
			Msg:  "密码错误,登录失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	cache.Rdb.Del(cache.Ctx, key)

	c.Data["json"] = Res{
		Code: 200,
		Msg:  "登录成功",
		Data: map[string]interface{}{
			"user_Id": user.ID,
		},
	}
	c.ServeJSON()
	return
}
